package com.jfinal.demo.plugins;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.plugin.druid.DruidPlugin;
import org.quartz.utils.ConnectionProvider;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Title:
 * Description:
 *
 * @version 2.0
 * @author: Yung Fu(FUYUNGCN AT GMAIL DOT com)
 * @since: 14-10-30 下午11:15
 */
public class QuartzConnectionProvider implements ConnectionProvider {

    private static final String DB_CONFIG = "a_little_config.txt";
    private DruidPlugin druidPlugin;

    @Override
    public Connection getConnection() throws SQLException {
        return druidPlugin.getDataSource().getConnection();
    }

    @Override
    public void initialize() throws SQLException {
        Properties properties = PropertiesUtil.loadPropertyFile(DB_CONFIG);
        druidPlugin = new DruidPlugin(
                properties.getProperty("jdbcUrl"),
                properties.getProperty("user"),
                properties.getProperty("password"),
                properties.getProperty("jdbcDriverClass"));
        // StatFilter提供JDBC层的统计信息
        druidPlugin.addFilter(new StatFilter());
        // WallFilter的功能是防御SQL注入攻击
        WallFilter wallFilter = new WallFilter();
        wallFilter.setDbType("mysql");
        druidPlugin.addFilter(wallFilter);
        druidPlugin.start();
    }

    @Override
    public void shutdown() throws SQLException {
        druidPlugin.stop();
    }
}
